package com.zrx.govern.component.easyexcel.starter.aop;

import com.zrx.govern.component.easyexcel.starter.annotation.DownloadTemplateExcel;
import com.zrx.govern.component.easyexcel.starter.config.ExcelConfigProperties;
import com.zrx.govern.component.easyexcel.starter.enums.ExcelEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * @author zhangxiaowei
 * @desc
 */
public class DownloadTemplateExcelReturnValueHandler implements HandlerMethodReturnValueHandler {

    public DownloadTemplateExcelReturnValueHandler(ExcelConfigProperties excelConfigProperties) {
        this.excelConfigProperties = excelConfigProperties;
    }

    private ExcelConfigProperties excelConfigProperties;

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return methodParameter.getMethodAnnotation(DownloadTemplateExcel.class) != null;
    }

    @Override
    public void handleReturnValue(Object o, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        DownloadTemplateExcel downloadTemplateExcel = methodParameter.getMethodAnnotation(DownloadTemplateExcel.class);
        if (StringUtils.isBlank(downloadTemplateExcel.template())) {
            throw new RuntimeException("注解@DownloadTemplateExcel模板不允许为空");
        }
        ExcelEnum excelEnum = ExcelEnum.getExcelEnumByValue(getExcelType(downloadTemplateExcel.template()));

        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        String templatePath = excelConfigProperties.getTemplatePath()+ File.separator+downloadTemplateExcel.template();
        InputStream bis = new ClassPathResource(templatePath).getInputStream();
        String filename = downloadTemplateExcel.template();
        if (StringUtils.isNotBlank(downloadTemplateExcel.name())) {
            filename = downloadTemplateExcel.name()+ excelEnum.getValue();
        }
        filename = URLEncoder.encode(filename, "UTF-8");
        response.setContentType(excelEnum.getContentType());
        response.setCharacterEncoding("utf8");
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read())!=-1){
            out.write(len);
            out.flush();
        }
        out.close();
        bis.close();
    }

    /**
     * 获取尾缀名
     * @param template
     * @return
     */
    private static String getExcelType(String template){
        return template.substring(template.lastIndexOf("."));
    }

}
